package xin.nick.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xin.nick.entity.Authority;
import xin.nick.mapper.AuthorityMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Nick
 * @date 2022/10/30
 */
@Component
public class AuthorityManager {

    @Autowired
    private AuthorityMapper authorityMapper;

    /**
     * 本地缓存的信息,如果是集群的情况需要用分布式缓存进行操作
     */
    private static Map<Long, Authority> authorityMap = null;
    private static List<Authority> authorityList = null;

    /**
     * 获取权限列表
     * @return
     */
    public List<Authority> getAuthorityList() {

        if (Objects.nonNull(authorityList)) {
            return authorityList;
        }

        authorityList = authorityMapper.selectList(null);
        return authorityList;
    }


    /**
     * 获取权限map
     * @return
     */
    public Map<Long, Authority> getAuthorityMap() {
        if (Objects.nonNull(authorityMap)) {
            return authorityMap;
        }

        List<Authority> authorityList = getAuthorityList();
        authorityMap = authorityList.stream()
                .filter(Objects::nonNull)
                .filter(authority -> Objects.nonNull(authority.getAuthorityId()))
                .collect(Collectors.toMap(Authority::getAuthorityId, Function.identity(), (v1,v2)->v2));


        return authorityMap;
    }


    /**
     * 获取所有权限的id列表
     * @return
     */
    public List<Long> getAuthorityIdList() {
        List<Authority> authorityList = getAuthorityList();
        List<Long> authorityIdList = authorityList.stream()
                .filter(Objects::nonNull)
                .map(Authority::getAuthorityId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return authorityIdList;
    }


    /**
     * 过滤存在的权限id,存在的才返回
     * @param filterAuthorityIdList
     * @return
     */
    public List<Long> filterExistingIdList(List<Long> filterAuthorityIdList) {
        if (CollectionUtils.isEmpty(filterAuthorityIdList)) {
            return new ArrayList<>();
        }
        List<Long> authorityIdList = getAuthorityIdList();
        List<Long> returnList = filterAuthorityIdList.stream()
                .filter(Objects::nonNull)
                .filter(authorityId -> authorityIdList.contains(authorityId))
                .collect(Collectors.toList());
        return returnList;
    }



}
